package com.perfma.xtest.tool;

import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.drawingml.x2006.main.CTGraphicalObject;
import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTAnchor;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDrawing;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * @author: junhui.si
 * @date: 2023-07-05 11:01
 **/
public class WordImgUtil2 {
    public static void main(String[] args) throws Exception {
        // 创建 word 文档对象
        XWPFDocument document = new XWPFDocument();
        // 获取图片路径
//        String picturePath = "/Users/sijunhui/Downloads/1-img/Xnip2023-03-15_15-21-49.jpg";
//        String picturePath = "/Users/sijunhui/Downloads/1-img/桌面原图/05.jpg";
//        String picturePath = "/Users/sijunhui/Downloads/1-img/WechatIMG178.png";
        String picturePath = "/Users/sijunhui/Downloads/1-img/Xnip2023-07-06_11-07-23.jpg";
//        String picturePath = "/Users/sijunhui/Downloads/1-img/Xnip2023-07-06_11-13-09.jpg";

        // 添加图片
        addImage(document, picturePath);

        // 保存Word文档
        FileOutputStream out = new FileOutputStream("/Users/sijunhui/Downloads/1/" + System.currentTimeMillis() + ".docx");
        document.write(out);
        out.close();
    }

    // 添加图片
    public static void addImage(XWPFDocument document, String picturePath) {
        try {
            XWPFParagraph paragraph = document.createParagraph();
            XWPFRun run;
//            run = paragraph.createRun();
//            run.setText("加斯科涅电斯科涅电脑上进度款出纳刷卡出纳双打卡出纳的声卡那可是加德纳才能看斯科涅电脑上进度款出纳刷卡出纳双打卡出纳的声卡那可是加德纳才能看斯科涅电脑上进度款出纳刷卡出纳双打卡出纳的声卡那可是加德纳才能看脑上进度款出纳刷卡出纳双打卡出纳的声卡那可是加德纳才能看");

            paragraph = document.createParagraph();
            paragraph.setAlignment(ParagraphAlignment.CENTER);

            run = paragraph.createRun();

            byte[] bytes = Files.readAllBytes(Paths.get(picturePath));
            ByteArrayInputStream bis = new ByteArrayInputStream(bytes);

            BufferedImage image = ImageIO.read(new ByteArrayInputStream(bytes));
            int oldWidth = image.getWidth();
            int oldHeight = image.getHeight();
            int maxWidth = 408;
            int maxHeight = 620;

            int newWidth = oldWidth;
            int newHeight = oldHeight;
            if (oldWidth > maxWidth || oldHeight > maxHeight) {
                //  计算缩放比例
                double scale = Math.min((double) maxWidth / oldWidth, (double) maxHeight / oldHeight);
                newWidth = (int) (oldWidth * scale);
                newHeight = (int) (oldHeight * scale);
            }
            XWPFPicture xwpfPicture = run.addPicture(bis, Document.PICTURE_TYPE_JPEG, "", Units.toEMU(newWidth), Units.toEMU(newHeight));
//            run = paragraph.createRun();
//            run.setFontSize(10);
//            run.setFontFamily("宋体");
            run.setText("图片描述");
//            run.addCarriageReturn();

            paragraph = document.createParagraph();
            run = paragraph.createRun();
            CTDrawing drawing = run.getCTR().getDrawingArray(0);
            CTGraphicalObject graphicalobject = drawing.getInlineArray(0).getGraphic();
            CTAnchor anchor = getAnchorWithGraphic(graphicalobject, "Xnip2023-07-06_11-07-23.jpg",
                    Units.toEMU(100), Units.toEMU(30),
                    Units.toEMU(30), Units.toEMU(0));
            drawing.setAnchorArray(new CTAnchor[]{anchor});
            drawing.removeInline(0);


//            paragraph = document.createParagraph();
//            run = paragraph.createRun();
//            run.setText("加斯科涅电斯科涅电脑上进度款出纳刷卡出纳双打卡出纳的声卡那可是加德纳才能看斯科涅电脑上进度款出纳刷卡出纳双打卡出纳的声卡那可是加德纳才能看斯科涅电脑上进度款出纳刷卡出纳双打卡出纳的声卡那可是加德纳才能看脑上进度款出纳刷卡出纳双打卡出纳的声卡那可是加德纳才能看");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static CTAnchor getAnchorWithGraphic(CTGraphicalObject graphicalobject,
                                                 String drawingDescr, int width, int height,
                                                 int left, int top) throws Exception {

        String anchorXML =
                "<wp:anchor xmlns:wp=\"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing\" "
                        + "simplePos=\"0\" relativeHeight=\"0\" behindDoc=\"1\" locked=\"0\" layoutInCell=\"1\" allowOverlap=\"1\">"
                        + "<wp:simplePos x=\"0\" y=\"0\"/>"
                        + "<wp:positionH relativeFrom=\"column\"><wp:posOffset>" + left + "</wp:posOffset></wp:positionH>"
                        + "<wp:positionV relativeFrom=\"paragraph\"><wp:posOffset>" + top + "</wp:posOffset></wp:positionV>"
                        + "<wp:extent cx=\"" + width + "\" cy=\"" + height + "\"/>"
                        + "<wp:effectExtent l=\"0\" t=\"0\" r=\"0\" b=\"0\"/>"
                        + "<wp:wrapTight wrapText=\"bothSides\">"
                        + "<wp:wrapPolygon edited=\"0\">"
                        + "<wp:start x=\"0\" y=\"0\"/>"
                        + "<wp:lineTo x=\"0\" y=\"21600\"/>" //Square polygon 21600 x 21600 leads to wrap points in fully width x height
                        + "<wp:lineTo x=\"21600\" y=\"21600\"/>"// Why? I don't know. Try & error ;-).
                        + "<wp:lineTo x=\"21600\" y=\"0\"/>"
                        + "<wp:lineTo x=\"0\" y=\"0\"/>"
                        + "</wp:wrapPolygon>"
                        + "</wp:wrapTight>"
                        + "<wp:docPr id=\"1\" name=\"Drawing 0\" descr=\"" + drawingDescr + "\"/><wp:cNvGraphicFramePr/>"
                        + "</wp:anchor>";

        CTDrawing drawing = CTDrawing.Factory.parse(anchorXML);
        CTAnchor anchor = drawing.getAnchorArray(0);
        anchor.setGraphic(graphicalobject);
        return anchor;
    }
}
